package cn.iocoder.yudao.module.promotion.fod.service;

import cn.iocoder.yudao.framework.common.exception.Assertions;
import cn.iocoder.yudao.module.promotion.fod.convert.FirstOrderDiscountVipRechargeConvert;
import cn.iocoder.yudao.module.promotion.fod.dao.FirstOrderDiscountVipRechargeMapper;
import cn.iocoder.yudao.module.promotion.fod.pojo.po.FirstOrderDiscountVipRecharge;
import cn.iocoder.yudao.module.promotion.fod.pojo.vo.FirstOrderDiscountVipRechargeVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.Collection;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 平台首单优惠（会员充值） Service 实现类
 *
 * @author 山野羡民
 */
@Slf4j
@Service
@Validated
public class FirstOrderDiscountVipRechargeServiceImpl extends FirstOrderDiscountInternalBaseService<FirstOrderDiscountVipRecharge, FirstOrderDiscountVipRechargeVO> implements FirstOrderDiscountVipRechargeService {
    private final Lock lock = new ReentrantLock();
    @Resource
    private FirstOrderDiscountVipRechargeMapper firstOrderDiscountVipRechargeMapper;

    @Override
    protected FirstOrderDiscountVipRechargeMapper getInjectedMapper() {
        return firstOrderDiscountVipRechargeMapper;
    }

    @Override
    public FirstOrderDiscountVipRechargeVO convertToViewObject(FirstOrderDiscountVipRecharge entity) {
        return FirstOrderDiscountVipRechargeConvert.INSTANCE.convert(entity);
    }

    @Override
    public FirstOrderDiscountVipRecharge getOrCreate(Long userId) {
        Assertions.isTrue(userId != null && userId > 0, "未获取到 userId");
        try {
            lock.lock();
            FirstOrderDiscountVipRecharge entity = getInjectedMapper().selectOne(FirstOrderDiscountVipRecharge::getUserId, userId);
            if (entity == null) {
                entity = new FirstOrderDiscountVipRecharge();
                entity.setUserId(userId);
                entity.setUsed(false);
                getInjectedMapper().insert(entity);
            }
            return entity;
        } finally {
            lock.unlock();
        }
    }

    @Override
    public Collection<Long> getUsedUserIds() {
        return firstOrderDiscountVipRechargeMapper.selectUsedUserIds();
    }

    @Override
    public void updateUnused(Long userId) {
        FirstOrderDiscountVipRecharge entity = getOrCreate(userId);
        if (Boolean.FALSE.equals(entity.getUsed())) {
            return;
        }
        entity.setUsed(false);
        getInjectedMapper().updateById(entity);
    }

}